define(["jquery", "template","migrate_jqprint","jqprint","scprit/department/view/template/assessmentScreening/assessmentScreeningQuestion-tpl.js",
    "scprit/department/vm/assessmentScreening/assessmentScreeningQuestion.ui.js","bbcare"], function ($, template,migrate,jqprint,tpl,$ui,$bb) {
    var servers={};
    var URL = $bb.baseUrl("followup") + "followup/service";
    var timer
    //题型格式处理：
    servers.dataDeal = function (data){
        var res=[];
        for( var item in data){
            var obj = {
                "nameT":item,
                'topic':data[item]
            };
            res.push(obj);
        }
        return res;
    };
    //题型状态处理：
    servers.quesStatus = function(question,questionAnswer){
        if(question instanceof Array && questionAnswer instanceof Array){//问卷题目循环嵌套 && 提交的结果存储为数组；
            for(var i =0;i<question.length;i++){
                for(var j =0;j<question[i].topic.length;j++){
                    var id = question[i].topic[j].id;
                    if($.inArray(id,questionAnswer)!="-1"){
                        question[i].topic[j].flag = true;
                    }
                }
            }
        }
        if(question instanceof Array && typeof(questionAnswer) == "object" && Object.prototype.toString.call(questionAnswer).toLowerCase() == "[object object]" && !questionAnswer.length){
            for(var i = 0;i<question.length;i++){
                var id = question[i].id;
                for(var j = 0;j< question[i].answer.length;j++){
                    if(question[i].answer[j].score == questionAnswer.map[id]){
                        question[i].answer[j].flag = true;
                    }
                }
            }
        }
        return question;
    };
    //处理答案：焦虑，抑郁，爱丁堡：
    servers.getAnswer = function(dom){
        var HashMap = this.hashmap(),hashMap = new HashMap();
        $(dom).find("input:checked").each(function(){
            var score = $(this).attr("score");
            var id = $(this).attr("name");
            hashMap.put(id,score);
        });
        return hashMap;
    };
    //分数计算:焦虑，抑郁，爱丁堡：
    servers.scoresDeal = function(dom,type){
        var HashMap = this.hashmap(), hashMapScore = new HashMap();
        var hashMap = this.getAnswer(dom);
        var scoresTotal= 0,name = [],lens,level,multiple=0;
        multiple = type == "EPDS" ? 1:1.25;
        for(var item in hashMap.map){
            scoresTotal += hashMap.map[item]*multiple;
            name.push(item);
        }
        scoresTotal = Math.floor(scoresTotal);
        lens = name.length;
        if(type == "SDS"){
            level = scoresTotal < 53 ? "正常":scoresTotal >= 53 && scoresTotal <=62 ? "轻度抑郁":scoresTotal >= 63 && scoresTotal <=72 ? "中度抑郁":"重度抑郁";
        }else if(type == "SAS"){
            level = scoresTotal < 50 ? "正常":scoresTotal >= 50 && scoresTotal <=59 ? "轻度焦虑":scoresTotal >= 60 && scoresTotal <=69 ? "中度焦虑":"重度焦虑";
        }else if(type == "EPDS"){
            level = scoresTotal >= 13 ? "可诊断为产后抑郁，建议及时综合干预":scoresTotal >= 9.5 ? "可诊断为产后抑郁":"正常";
        }
        hashMapScore.put("level",level);
        hashMapScore.put("lens",lens);
        hashMapScore.put("scoresTotal",scoresTotal);
        return {
            "hash":hashMap,
            "name":name,
            "scores":hashMapScore,
            "lens":lens
        }
    };
    //渲染答案：焦虑，抑郁，爱丁堡：
    servers.scriptAnswer = function(dom,res,type){
        $('#myModal').modal('show');
        if(type == "EPDS"){
            $ui.postpartumResultInit({"id":dom,"data":res});
        }else{
            $ui.postpartumResultInit({"id":dom,"data":res});
        }
    };

    //获取题目：
    servers.getParams = function (exam , id){
        return {
            "examinationPaperName":exam,
            "userId":id
        }
    };
    servers.getParamsTem = function (exam , id,createTime){
        return {
            "examinationPaperName":exam,
            "userId":id,
            "createTime":createTime
        }
    };
    servers.getQuestion = function (params , callback){
        $bb.ajax({
            url: URL + "/patient/evaluation/getAllPostion",
            data: JSON.stringify({
                data: params
            }),
            success: function (data) {
                if(data.success){
                    callback(data);
                }
            }
        });
    };
    //获取分数：
    servers.scoreParams = function (exam , posId ,posSco,userId,business){
        posId = posId instanceof Object ? JSON.stringify(posId) : posId;
        posSco = posSco instanceof Object ? JSON.stringify(posSco) : posSco;
        return {
                "examinationPaperName":exam,
                "postionIds":posId,
                "postionScores":posSco,
                "userId":userId,
                "business":business
        }
    };
    //获取分数bsid2：
    servers.scoreParamsBsid2 = function (exam , posId ,posSco,userId){
        //posId = posId instanceof Object ? JSON.stringify(posId) : posId;
        posSco = posSco instanceof Object ? JSON.stringify(posSco) : posSco;
        return {
            "examinationPaperName":exam,
            "postionIds":posId,
            "postionScores":posSco,
            "userId":userId
        }
    };
    servers.getScore = function (params,callback){
        $bb.ajax({
            url: URL + "/patient/evaluation/getScore",
            data: JSON.stringify({
                data: params
            }),
            success: function (data) {
                if(data.success){
                    callback(data);
                }else{
                    $bb.toastShow("保存失败",1500);
                }
            }
        });
    };
    //获取患者信息：
    servers.infoParams = function(userId){
        return {
            "patientId":userId
        }
    };
    servers.infoParamsBsid2 = function(userId,type){
        return {
            "patientId":userId,
            "examinationPaperName": type
        }
    };
    servers.getInfo = function(params,callback){
        $bb.ajax({
            url: URL + "/patient/patientInfoPtId",
            data: JSON.stringify({
                data: params
            }),
            success: function (data) {
                if(data.success){
                    callback(data);
                }
            }
        });
    };
    //获取历史记录列表：
    servers.hisParams = function(userId,type,page,rows){
        return {
            "userId": userId,
            "examinationPaperName": type,
            "page": page,
            "rows": rows
        }
    };
    servers.history = function(params,callback){
        $bb.ajax({
            url: URL + "/patient/evaluation/getHistoryScore",
            data: JSON.stringify({
                data: params
            }),
            success: function (data) {
                if(data.success){
                    callback(data);
                }
            }
        });
    };
    //获取曲线值：
    servers.trendsParams = function(userId,evaId,exam){
        return {
            "userId":userId,
            "evaluationId"	:evaId,
            "examinationPaperName":exam
        }
    };
    servers.trends = function(params,callback){
        $bb.ajax({
            url: URL + "/patient/evaluation/albertacurvedata",
            data: JSON.stringify({
                data: params
            }),
            success: function (data) {
                if(data.success){
                    callback(data);
                }
            }
        });
    };
    //获取建议接口；
    servers.getGuidesParams = function(userId,exam,evaId){
        return {
            "evaluationId":evaId,
            "examinationPaperName": exam,
            "userId": userId
        }
    };
    servers.getGuidesParamsBsid3 = function(userId,exam,evaId,age){
        return {
            "evaluationId":evaId,
            "age":typeof age == 'number'? age.toString():age,
            "examinationPaperName": exam,
            "userId": userId
        }
    };
    servers.getGuidesParamsTem = function(userId,exam,evaId,type){
        return {
            "evaluationId":evaId,
            "type":type,
            "examinationPaperName": exam,
            "userId": userId
        }
    };
    servers.getGuides = function(params,callback){
        $bb.ajax({
            url: URL + "/patient/evaluation/getGuide",
            data: JSON.stringify({
                data: params
            }),
            success: function (data) {
                if(data.success){
                    callback(data);
                }
            }
        });
    };
    //修改建议接口；
    servers.modifyGuidesParams = function(userId,evaId,guides,remark){
        return {
            "userId":userId,
            "evaluationId":evaId,
            "guide":guides,
            "remark":remark
        }
    };
    servers.modifyGuides = function(params,callback){
        $bb.ajax({
            url: URL + "/patient/evaluation/guidemodify",
            data: JSON.stringify({
                data: params
            }),
            success: function (data) {
                if(data.success){
                    callback(data);
                }
            }
        });
    };
    //获取评估记录详情接口；
    servers.reportParams = function(userId,evaId){
        return {
            "userId":userId,
            "evaluationId"	:evaId
        }
    };
    servers.reportParamsBsid2 = function(userId,evaId,type){
        return {
            "userId":userId,
            "evaluationId"	:evaId,
            "examinationPaperName": type
        }
    };
    servers.report = function(params,callback){
        $bb.ajax({
            url: URL + "/patient/evaluation/scoredetail",
            data: JSON.stringify({
                data: params
            }),
            success: function (data) {
                if(data.success){
                    callback(data);
                }
            }
        });
    };
    //列表搜索框：
    servers.isNumber = function(obj){
        var reg = /^[0-9]*$/;
        return reg.test(obj);
    };

    servers.searchParams = function(key,flag){
        var params={};
        if(flag == "1"){
            params={
                "flag":2,
                "phoneNum":key
            }
        }else{
            params={
                "flag":2,
                "patientName":key
            }
        }
        return params;
    };
    servers.search = function(params,callback,flag){
        timer && clearTimeout(timer)
        timer = setTimeout(function () {
        $bb.ajax({
            url: URL + "/patient/patientQueueListQuery",
            data: JSON.stringify({
                data: params
            }),
            success: function (data) {
                if(data.success){
                    flag ? callback(data,flag):callback(data);
                }
            }
        })
        }, 500)
    };
    servers.hashmap = function (){
        function HashMap(){
            this.map = {};
        }
        HashMap.prototype = {
            put : function(key , value){
                this.map[key] = value;
            },
            get : function(key){
                if(this.map.hasOwnProperty(key)){
                    return this.map[key];
                }
                return null;
            },
            remove : function(key){
                if(this.map.hasOwnProperty(key)){
                    return delete this.map[key];
                }
                return false;
            },
            removeAll : function(){
                this.map = {};
            },
            keySet : function(){
                var _keys = [];
                for(var i in this.map){
                    _keys.push(i);
                }
                return _keys;
            }
        };
        HashMap.prototype.constructor = HashMap;
        return HashMap;
    };
    //返回当前时间：
    servers.getNowFormatDate=function(){
        var date = new Date();
        var seperator1 = "-";
        var month = date.getMonth() + 1;
        var strDate = date.getDate();
        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
        }
        var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate;
        return currentdate;
    };
    //计算天数差的函数，通用 ：
    servers.dateDiff=function(sDate1,  sDate2){
        function addZore(num) { return num < 10 ? '0' + num : num }
        /**
         * 兼容 时间戳 格式的日期
         */
        sDate2 = String(sDate2).indexOf('-') > -1 ? String(sDate2) : Number(sDate2)
        var d1 = new Date(sDate1)
        var d2 = new Date(sDate2)
        sDate1 = d1.getFullYear() + '-' + addZore(d1.getMonth() + 1) + '-' + addZore(d1.getDate())
        sDate2 = d2.getFullYear() + '-' + addZore(d2.getMonth() + 1) + '-' + addZore(d2.getDate())

        var  aDate,  oDate1,  oDate2,  iDays;
        aDate  =  sDate1.split("-");
        oDate1  =  new  Date(parseFloat(aDate[0]),parseFloat(aDate[1])-1,parseFloat(aDate[2]));    //创建时间；
        aDate  =  sDate2.split("-");
        oDate2  =  new  Date(parseFloat(aDate[0]),parseFloat(aDate[1])-1,parseFloat(aDate[2]));    //创建时间；
        iDays  =  parseInt(Math.abs(oDate1  -  oDate2)  /  1000  /  60  /  60  /24);    //把相差的毫秒数转换为天数
        return  iDays
    };
    //实际年龄：
    servers.getAge=function(day){
        var y = parseInt(day/365)==0 ? "":parseInt(day/365);
        var m = parseInt(day%365/30)==0 ? "":parseInt(day%365/30);
        var w = parseInt(day%365%30/7)==0 ? '':parseInt(day%365%30/7);
        var d = parseInt(day%365%30%7)==0 ? '':parseInt(day%365%30%7);
        var age;
        if(y){
            age = y + "岁" + (m >= 1 ? m + "月龄" : "");
        }else{
            if( m >= 3 ){
                age = m + "月龄" + (parseInt(day%365%30))+"天";
            }else{
                var days = day;
                age = (parseInt(days/7) > 0 ? parseInt(days/7)+"周" : "") + parseInt(days%7)+"天";
            }
        }
        return age
    }
    //纠正年龄：
    servers.age=function(acturalDay,pregnance){
        var day,age2;
        if(parseFloat(pregnance) < 37*7 && acturalDay < 2*365 ){
            var difD=40*7-parseFloat(pregnance); //判断与预产期差了多少天；
            day=acturalDay-difD;
            if(day>0){
                age2=this.getAge(day);
            }else{
                age2=day+"天";
            }
        }else{
            day=acturalDay;
            age2=this.getAge(day);
        }
        return age2;
    }
    //月龄计算：
    servers.monthAge = function(acturalDay,pregnance){
        var days;
        if(pregnance < 37*7 && acturalDay < 365*2){
            days = acturalDay - (40*7 - pregnance);
        }else{
            days = acturalDay;
        }
        var monthAge = (days/30).toFixed(3);
        return monthAge;
    };
    /*
     * 月龄计算：1.2月
     * */
    servers.getMonth = function(diff,pregnanceDay){
        pregnanceDay = pregnanceDay ? pregnanceDay:280;
        var days,monthAge , flag;//flag == 1,实际月龄；flag == 2 ,纠正月龄；
        if(diff < 2*365 && pregnanceDay < 37*7){
            flag = 2;
            days = diff - (40*7 -pregnanceDay);
        }else{
            flag = 1;
            days = diff;
        }
        monthAge = (days / 30).toFixed(1);
        return {
            "flag":flag,
            "monthAge":monthAge
        }
    };
    /*
     * 月龄计算：
     *
     * */
    servers.getMonthAge = function(diff,pregnanceDay){
        pregnanceDay = pregnanceDay ? pregnanceDay:280;
        var days,monthAge ,day, flag;//flag == 1,实际月龄；flag == 2 ,纠正月龄；
        if(diff < 2*365 && pregnanceDay < 37*7){
            flag = 2;
            days = diff - (40*7 -pregnanceDay);
        }else{
            flag = 1;
            days = diff;
        }
        monthAge = parseInt(days/30) > 0 ? parseInt(days/30) + "月龄":'';
        day = parseInt(days%30) > 0 ? parseInt(days%30) + "天":'';
        return {
            "flag":flag,
            "monthAge":monthAge + day,
            "month": parseInt(days/30)
        }
    };
    //打印：
    servers.print = function(dom){
        var $pc=$(dom);
        $pc.jqprint({
            debug: false, //如果是true则可以显示iframe查看效果（iframe默认高和宽都很小，可以再源码中调大），默认是false
            importCSS: true, //true表示引进原来的页面的css，默认是true。（如果是true，先会找$("link[media=print]")，若没有会去找$("link")中的css文件）
            printContainer: true, //表示如果原来选择的对象必须被纳入打印（注意：设置为false可能会打破你的CSS规则）。
            operaSupport: true//表示如果插件也必须支持歌opera浏览器，在这种情况下，它提供了建立一个临时的打印选项卡。默认是true
        });
    };
    return servers;
});